package put_bot

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"os"
	"net/http"
	"time"
	"fmt"
	"mime/multipart" 
    "path/filepath"  
    "io"   
	"auto/src/set_config"          
)

//发功文字消息
func sendWebhookMessage(content string,Robot_Webhook string) (int, string, error) { // 发送消息到指定的Webhook URL
	requestBody := map[string]interface{}{ 
		"type": "text",
		"textMsg": map[string]interface{}{
			"content": content,
		},
	}

	jsonData, _ := json.Marshal(requestBody) // 将请求体编码为JSON

	// 创建HTTP客户端并发送POST请求

	client := &http.Client{Timeout: 30 * time.Second}
	req, err := http.NewRequest(
		"POST",
		Robot_Webhook,
		bytes.NewBuffer(jsonData),
	)
	if err != nil {
		return 0, "", err
	}

	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		return 0, "", err
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	return resp.StatusCode, string(body), nil
}
//发送图片消息
func sendWebhookMge(fileId string,Robot_Webhook string) (int, string, error) { // 发送消息到指定的Webhook URL
	requestBody := map[string]interface{}{ 
		"type": "image",
		"imageMsg": map[string]interface{}{
			"fileId": fileId,
		},
	}

	jsonData, _ := json.Marshal(requestBody) // 将请求体编码为JSON

	// 创建HTTP客户端并发送POST请求

	client := &http.Client{Timeout: 30 * time.Second}
	req, err := http.NewRequest(
		"POST",
		Robot_Webhook,
		bytes.NewBuffer(jsonData), 
	)
	if err != nil {
		return 0, "", err
	}

	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		return 0, "", err
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	return resp.StatusCode, string(body), nil
}

//发送文件消息
func sendWebhookFile(fileId string,Robot_Webhook string) (int, string, error) { // 发送消息到指定的Webhook URL
	requestBody := map[string]interface{}{ 
		"type": "file",
		"fileMsg": map[string]interface{}{
			"fileId": fileId,
		},
	}

	jsonData, _ := json.Marshal(requestBody) // 将请求体编码为JSON

	// 创建HTTP客户端并发送POST请求

	client := &http.Client{Timeout: 30 * time.Second}
	req, err := http.NewRequest(
		"POST",
		Robot_Webhook,
		bytes.NewBuffer(jsonData),
	)
	if err != nil {
		return 0, "", err
	}

	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		return 0, "", err
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	return resp.StatusCode, string(body), nil
}


//文件上传
func uploadFile(filePath string,File_Webhook string) (string, error) {
    // 打开文件
    file, err := os.Open(filePath)
    if err != nil {
        return "", fmt.Errorf("打开文件失败: %v", err)
    }
    defer file.Close()

    // 创建 multipart form-data 请求体
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    
    // 创建文件字段
    part, err := writer.CreateFormFile("file", filepath.Base(filePath))
    if err != nil {
        return "", fmt.Errorf("创建表单文件失败: %v", err)
    }
    
    // 拷贝文件内容
    _, err = io.Copy(part, file)
    if err != nil {
        return "", fmt.Errorf("拷贝文件内容失败: %v", err)
    }
    
    // 关闭writer
    err = writer.Close()
    if err != nil {
        return "", fmt.Errorf("关闭writer失败: %v", err)
    }

    // 创建HTTP客户端并发送POST请求
    client := &http.Client{Timeout: 30 * time.Second}
    req, err := http.NewRequest(
        "POST",
        File_Webhook,
        body,
    )
    if err != nil {
        return "", err
    }

    // 设置请求头
    req.Header.Set("Content-Type", writer.FormDataContentType())

    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    // 读取响应
    respBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", fmt.Errorf("读取响应失败: %v", err)
    }

    // 检查HTTP状态码
    if resp.StatusCode != http.StatusOK {
        return "", fmt.Errorf("上传失败，状态码: %d, 响应: %s", resp.StatusCode, string(respBody))
    }

    // 解析响应JSON获取fileId
    var result map[string]interface{}
    err = json.Unmarshal(respBody, &result)
    if err != nil {
        return "", fmt.Errorf("解析响应JSON失败: %v", err)
    }

    // 提取content中的id
    content, ok := result["content"].(map[string]interface{})
    if !ok {
        return "", fmt.Errorf("响应中缺少content字段")
    }

    fileId, ok := content["id"].(string)
    if !ok {
        return "", fmt.Errorf("响应中缺少id字段")
    }

    return fileId, nil
}

func Step(content string,fileName string,config *set_config.Config) { //
	// 顺序发送三种消息类型
	//单发文字消息，单发图片消息，单发文件消息
	//文字信息
	fmt.Printf("正在准备发送文字中...\r\n")
	if _,_, err := sendWebhookMessage(content,config.Data.Robot_Webhook); err != nil {
		fmt.Printf("发送失败:%s\r\n", err.Error())
		return
	} 
	fmt.Printf("文字发送成功\r\n")
	//图片信息
	fmt.Printf("正在准备发送图片中...\r\n")
	img_path := config.Data.RootPath+"out/img/" + fileName + ".png"
	fileId, err := uploadFile(img_path,config.Data.File_Webhook)
	if err != nil {
		fmt.Printf("文件上传失败: %v\r\n", err)
		return
	}
	if _,_, err := sendWebhookMge(fileId,config.Data.Robot_Webhook); err != nil {
		fmt.Printf("发送失败:%s\r\n", err.Error())
		return
	}
	fmt.Printf("图片发送成功\r\n")
	//文件信息
	fmt.Printf("正在准备发送文件中...\r\n")
	file_path := config.Data.RootPath+ "out/excel/" + fileName + ".xlsx"
	fileId, err = uploadFile(file_path,config.Data.File_Webhook)
	if err != nil {
		fmt.Printf("文件上传失败: %v\r\n", err)
		return
	}
	if _,_, err := sendWebhookFile(fileId,config.Data.Robot_Webhook); err != nil {
		fmt.Printf("发送失败:%s\r\n", err.Error())
		return
	}
	fmt.Printf("文件发送成功\r\n")
	fmt.Printf("一次脚本完成\r\n")
}
